package jjn.round1;

import commons.TreeNode;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Jjn
 * @since 2023/5/1 12:41
 */
public class LeetCode337_RobV3 {
    
    
    /**
     * Choose current node.
     */
    private final Map<TreeNode, Integer> chosen = new HashMap<>();
    /**
     * Do not choose current node.
     */
    private final Map<TreeNode, Integer> givenUp = new HashMap<>();
    
    public int rob(TreeNode root) {
        dfs(root);
        return Math.max(chosen.getOrDefault(root, 0), givenUp.getOrDefault(root, 0));
    }
    
    private void dfs(TreeNode root) {
        if (root == null) {
            return;
        }
        dfs(root.left);
        dfs(root.right);
        chosen.put(root, root.val + givenUp.getOrDefault(root.left, 0) + givenUp.getOrDefault(root.right, 0));
        givenUp.put(root, Math.max(chosen.getOrDefault(root.left, 0), givenUp.getOrDefault(root.left, 0))
                + Math.max(chosen.getOrDefault(root.right, 0), givenUp.getOrDefault(root.right, 0)));
    }
}
